package com.example.javabasic.thread.classtwo.workthread.demo2;

import com.example.javabasic.thread.classtwo.workthread.demo1.Request;
import com.example.javabasic.thread.classtwo.workthread.demo2.future.FutureService;
import com.example.javabasic.thread.classtwo.workthread.demo2.future.TaskFuture;

import java.util.concurrent.Callable;

/**
 * @description 消息队列
 * @Author Lin FuYuan
 * @date 2021/2/25
 */
public class TaskQueue {
    //队列长度大小
    private int size;
    //头
    private int head;
    //尾
    private int tail;
    //总数
    private int count;
    //任务队列

    private TaskFuture[] futures;

    public TaskQueue(int size){
        this.size = size;
        init();
    }
    //初始化
    public void init(){
        this.head = 0;
        this.tail = 0;
        this.count = 0;
        this.futures = new TaskFuture[this.size];
    }

    //队列中放入
    public synchronized TaskFuture put(Callable request) {
        FutureService futureService = new FutureService();
        TaskFuture submit = futureService.submit(request);
        //当 count >  队列长度  说明满了
        while (this.count >= this.futures.length) {
            try {
                this.wait();
            } catch (InterruptedException e) {

            }
        }
        //循环队列
        this.futures[this.tail] = submit;
        this.tail = this.tail+1 % this.futures.length;
        this.count++;
        //添加了任务到队列中  并且唤醒任务线程
        this.notifyAll();
        return submit;
    }

    //队列中取出
    public synchronized TaskFuture take() {
        while (count <= 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        TaskFuture request = this.futures[this.head];
        this.head = this.head+1 % futures.length;
        this.count--;
        System.out.println("工人 "+Thread.currentThread().getName()+"消费了->"+ request.toString()+ "剩余:"+this.count);
        return request;
    }


}
